package com.anos.smsfun.activities;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.anos.smsfun.R;
import com.anos.smsfun.adapter.IconListAdapter;
import com.anos.smsfun.adapter.SearchSusgesstionsAdapter;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.model.MessageItem;
import com.anos.smsfun.services.smsDeliveredReceiver;
import com.anos.smsfun.services.smsSentReceiver;
import com.anos.smsfun.task.QueryUtils;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.EmoticonsMgr;
import com.anos.smsfun.utility.Utils;

public class ChooseContactSendMSGActivity extends Activity implements
        OnClickListener, OnItemSelectedListener, OnItemClickListener {

    private LinearLayout l_layout;
    private View l_right;
    private Button btnAddIcon;
    private Button btnSend;
    private Button btnAddContact;
    private EditText edInputText;
    private AutoCompleteTextView mSearchAuto;
    private ScrollView scrollView;

    private TextView tvTitleBold;
    private TextView tvTitleSmall;

    private SMSFunDataCache mSmsFunDataCache;
    private ArrayList<ContactsWrapper> mListContacts = new ArrayList<ContactsWrapper>();
    private ArrayList<MessageItem> mMessageItems = new ArrayList<MessageItem>();
    private ArrayList<String> mListName = new ArrayList<String>();
    private ArrayList<String> mListPhone = new ArrayList<String>();
    private ArrayList<String> mListPhoneSendMSG = new ArrayList<String>();
    private SearchSusgesstionsAdapter mAdapter;

    private BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

    private boolean mShowwingListIcon;
    private ArrayList<Integer> mArrIdIcons = new ArrayList<Integer>();
    private LinearLayout l_add_layout_icon;

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DefConstants.WHAT_SENT_RESULT_OK:
                    break;

                case DefConstants.WHAT_SENT_RESULT_NO_SERVICE:
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact_send);

        Utils.setUpActionBar(this);
        /**
         * set title view
         */
        LayoutInflater inflator = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflator.inflate(R.layout.title_view, null);
        tvTitleBold = (TextView) v.findViewById(R.id.tvTitle_ab);
        tvTitleSmall = (TextView) v.findViewById(R.id.tvNumber_ab);
        tvTitleBold.setText(getString(R.string.title_new_msg));
        tvTitleSmall.setText(getString(R.string.title_hint_new_msg));

        getActionBar().setCustomView(v);

        findViewByIdAll();

        // init
        mSmsFunDataCache = SMSFunDataCache.getInstance(this);

        // get bundle
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String strText = bundle
                    .getString(DefConstants.ACTION_VIEW_FIND_CONTACT);
            edInputText.setText(strText);
        }

        // get list data
        getContactList();

        mAdapter = new SearchSusgesstionsAdapter(this,
                android.R.layout.simple_dropdown_item_1line, mListName);
        mSearchAuto.setThreshold(1);
        mSearchAuto.setAdapter(mAdapter);
        mSearchAuto.setOnItemSelectedListener(this);
        mSearchAuto.setOnItemClickListener(this);
    }

    private void findViewByIdAll() {
        l_add_layout_icon = (LinearLayout) findViewById(R.id.layout_add_layout_icon);
        mSearchAuto = (AutoCompleteTextView) findViewById(R.id.autoComplete_input);
        edInputText = (EditText) findViewById(R.id.edInputMSG_choose);
        btnAddIcon = (Button) findViewById(R.id.btnInsertIcon_choose);
        btnAddContact = (Button) findViewById(R.id.btnAddContact_choose);
        btnSend = (Button) findViewById(R.id.btnSend_choose);
        l_layout = (LinearLayout) findViewById(R.id.layout_add_msg);
        scrollView = (ScrollView) findViewById(R.id.scroll_msg_send);

        btnAddContact.setOnClickListener(this);
        btnAddIcon.setOnClickListener(this);
        btnSend.setOnClickListener(this);
        mSearchAuto.setFocusable(true);
    }

    /**
     * get list contact
     */
    private void getContactList() {
        mListContacts = mSmsFunDataCache.getContactList();
        for (ContactsWrapper contact : mListContacts) {
            mListName.add(contact.getDisplayName());
            mListPhone.add(contact.getDisplayNumber());
        }
    }

    @Override
    protected void onPause() {
        try {
            if (smsSentReceiver != null) {
                unregisterReceiver(smsSentReceiver);
            }
            if (smsDeliveredReceiver != null) {
                unregisterReceiver(smsDeliveredReceiver);
            }
        } catch (Exception ex) {
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mMessageItems.clear();
        mMessageItems = null;
        mListContacts.clear();
        mListContacts = null;
        mListPhoneSendMSG.clear();
        mListPhoneSendMSG = null;
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                overridePendingTransition(0, R.anim.exit_slide_right);
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.exit_slide_right);
        return;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnAddContact_choose:
                Intent intent = new Intent(ChooseContactSendMSGActivity.this,
                        SelectContactActivity.class);
                startActivityForResult(intent, DefConstants.REQ_CODE_SELECT_CONTACT);
                overridePendingTransition(0, R.anim.exit_slide_left);
                break;
            case R.id.btnSend_choose:
                final String body = edInputText.getText().toString().trim();
                if (body.length() == 0)
                    return;
                if (mListPhoneSendMSG.size() == 0) {
                    Builder builder = new Builder(ChooseContactSendMSGActivity.this);
                    builder.setMessage(ChooseContactSendMSGActivity.this
                            .getString(R.string.toast_input_contact_error));
                    builder.setPositiveButton(ChooseContactSendMSGActivity.this
                                    .getString(R.string.ok),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            }
                    );
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                    return;
                }
                MessageItem msgItem = null;
                for (String phone : mListPhoneSendMSG) {
                    msgItem = new MessageItem();
                    msgItem.setAddress(phone);
                    msgItem.setType(2);
                    msgItem.setLongDate(System.currentTimeMillis());
                    msgItem.setNameDisplay("");
                    msgItem.setBody(body);
                    msgItem.setStatus(1);

                    // send msg
                    if (sendSMS(msgItem)) {
                        // insert
                        QueryUtils.insertSmsSentItem(
                                ChooseContactSendMSGActivity.this, msgItem);
                    }
                }
                // refresh list
                edInputText.setText("");
                mMessageItems.add(0, msgItem);
                refreshDataList();

                break;

            case R.id.btnInsertIcon_choose:
                includeLayoutAddIcon();
                break;

            default:
                break;
        }
    }

    private void refreshDataList() {
        if (mMessageItems == null || mMessageItems.isEmpty())
            return;

        // duyet list de add vao layout
        l_layout.removeAllViews();
        for (int i = mMessageItems.size() - 1; i >= 0; i--) {
            final MessageItem msgItem = mMessageItems.get(i);
            l_right = getLayoutInflater().inflate(
                    R.layout.item_conversation_right, null);
            l_right.setId(msgItem.getId());
            final TextView tvBody = (TextView) l_right
                    .findViewById(R.id.tvBody_conv_right);
            TextView tvTime = (TextView) l_right
                    .findViewById(R.id.tvTime_conv_right);
            TextView tvStatus = (TextView) l_right
                    .findViewById(R.id.tvIsSending_conv_right);
            tvTime.setText(msgItem
                    .getFormatDate(DefConstants.DATE_FORMAT_DDMMHHMM));

            Spannable textBody = EmoticonsMgr.getSmiledText(ChooseContactSendMSGActivity.this, msgItem.getBody());
            tvBody.setText(textBody);

            // status
            tvStatus.setVisibility(View.GONE);

            l_layout.addView(l_right);
        }

        // scroll xuống tin nhắn cuối cùng
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> av, View v, int position, long id) {
        // Get Array index value for selected name
        int i = mListName.indexOf("" + av.getItemAtPosition(position));

        // If name exist in name ArrayList
        if (i >= 0) {
            // Get Phone Number
            mListPhoneSendMSG.add(mListPhone.get(i));

            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            // Show Alert
            Toast.makeText(
                    getBaseContext(),
                    av.getItemAtPosition(position) + " [" + mListPhone.get(i)
                            + "]", Toast.LENGTH_SHORT
            ).show();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> av, View v, int position, long id) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNothingSelected(AdapterView<?> av) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        Toast.makeText(getBaseContext(), "### - " + mListPhoneSendMSG.size(),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (requestCode == DefConstants.REQ_CODE_SELECT_CONTACT) {
            Bundle bundle = data.getExtras();
            ArrayList<ContactsWrapper> contactSelecteds = bundle
                    .getParcelableArrayList(DefConstants.PUT_LIST_SELECT_CONTACT);
            if (contactSelecteds.size() == 0)
                return;

            updateListPhoneSelect(contactSelecteds);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Hien thi danh sach contact dc chon len textbox
     */
    private void updateListPhoneSelect(
            ArrayList<ContactsWrapper> contactSelecteds) {
        mListPhoneSendMSG.clear();
        String titleBold = "";
        String titleSmall = "";
        for (ContactsWrapper contact : contactSelecteds) {
            mListPhoneSendMSG.add(contact.getDisplayNumber());
            titleBold += contact.getDisplayName() + "; ";
            titleSmall += contact.getDisplayNumber() + "; ";
            addItemContact(contact.getDisplayNumber(), contact.getDisplayName());
        }

        // update UI
        if (titleBold.length() > 30)
            titleBold = titleBold.substring(0, 30) + "...";
        if (titleSmall.length() > 30)
            titleSmall = titleSmall.substring(0, 30) + "...";
        tvTitleBold.setText(titleBold);
        tvTitleSmall.setText(titleSmall);
    }

    /**
     * add item contact to textbox [Token edittext]
     */
    private void addItemContact(String phone, String name) {
        final SpannableStringBuilder sb = new SpannableStringBuilder();
        TextView tv = createContactTextView(phone, name);
        BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(tv);
        bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());

        sb.append(name + " ");
        sb.setSpan(new ImageSpan(bd), sb.length() - (name.length() + 1),
                sb.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mSearchAuto.append(sb);
        mSearchAuto.setSelection(mSearchAuto.getText().length());
    }

    public TextView createContactTextView(String tag, String text) {
        // creating textview dynamically
        TextView tv = new TextView(this);
        tv.setText(text);
        tv.setTextSize(30);
        tv.setBackgroundResource(R.drawable.bg_bubble_text);
        tv.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                R.drawable.ic_search_close, 0);
        return tv;
    }

    @SuppressWarnings("deprecation")
    public static Object convertViewToDrawable(View view) {
        int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        view.measure(spec, spec);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(),
                view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        c.translate(-view.getScrollX(), -view.getScrollY());
        view.draw(c);
        view.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = view.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        view.destroyDrawingCache();
        return new BitmapDrawable(viewBmp);

    }

    /**
     * *********************** ICON ***********************
     */
    // load list icon
    private void includeLayoutAddIcon() {
        if (mShowwingListIcon) {
            l_add_layout_icon.removeAllViews();
            mShowwingListIcon = false;
            // show keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(edInputText, 0);
        } else {
            // hide keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edInputText.getWindowToken(), 0);

            // include view
            View view = getLayoutInflater().inflate(
                    R.layout.layout_display_icon, null);
            GridView gvIconList = (GridView) view.findViewById(R.id.gvListIcon);

            // numscolumn
            float scalefactor = getResources().getDisplayMetrics().density * 60;
            int number = getWindowManager().getDefaultDisplay().getWidth();
            int columns = (int) ((float) number / (float) scalefactor);
            gvIconList.setNumColumns(columns);

            // load all icon
            mArrIdIcons = EmoticonsMgr.getListIcons(this);

            IconListAdapter adapter = new IconListAdapter(this, mArrIdIcons);
            gvIconList.setAdapter(adapter);

            l_add_layout_icon.addView(view);
            mShowwingListIcon = true;

            gvIconList.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    final int idRes = mArrIdIcons.get(i);

                    int cursorPosition = edInputText.getSelectionStart();
                    String tempFirst = edInputText.getText().toString().substring(0, cursorPosition);
                    String tempLast = "";
                    if (cursorPosition < edInputText.getText().length())
                        tempLast = edInputText.getText().toString().substring(cursorPosition, edInputText.getText().length());

                    tempFirst += EmoticonsMgr.getKeyByValue(idRes);
                    tempFirst += tempLast;

                    edInputText.setText(EmoticonsMgr.getSmiledText(ChooseContactSendMSGActivity.this, tempFirst));
                    edInputText.setSelection(edInputText.getText().length());
                }
            });
        }
    }

    // ////////////////////////////////////////////////////////////////
    // SEND SMS
    // ////////////////////////////////////////////////////////////////

    /**
     * send sms to another device
     */
    private boolean sendSMS(final MessageItem msgItem) {
        try {
            final int MAX_SMS_MESSAGE_LENGTH = 160;
            final String SENT = "SMS_SENT";
            final String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                    new Intent(SENT), 0);
            PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                    new Intent(DELIVERED), 0);

            smsSentReceiver = new smsSentReceiver(msgItem, mHandler);
            smsDeliveredReceiver = new smsDeliveredReceiver(msgItem);

            /**
             * --when the SMS has been sent
             */
            registerReceiver(smsSentReceiver, new IntentFilter(SENT));

            /**
             * --when the SMS has been delivered
             */
            registerReceiver(smsDeliveredReceiver, new IntentFilter(DELIVERED));

            SmsManager smsManager = SmsManager.getDefault();
            int length = msgItem.getBody().length();
            if (length > MAX_SMS_MESSAGE_LENGTH) {
                ArrayList<String> messagelist = smsManager
                        .divideMessage(msgItem.getBody());
                smsManager.sendMultipartTextMessage(msgItem.getAddress(), null,
                        messagelist, null, null);
            } else {
                smsManager.sendTextMessage(msgItem.getAddress(), null,
                        msgItem.getBody(), sentPI, deliveredPI);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(
                    ChooseContactSendMSGActivity.this,
                    ChooseContactSendMSGActivity.this
                            .getString(R.string.toast_input_contact_error),
                    Toast.LENGTH_SHORT
            ).show();
            return false;
        }
    }

}
